import Vue from 'vue'
import Vuex from 'vuex'
import store from '../store'
import utils from './utils'

let util = new utils()
let vue = Vue.use(Vuex)
function isNotEmpty(row, column) {
  return row.hasOwnProperty(column.property)
    && row[column.property] != null
    && row[column.property] !== undefined
}

export default class approveUtils {
  constructor(options) {
    this.cols = {
      name: {
          title: '姓名',
          formatter: (row) => this.stringFormatter(row, 'name')
      },
      workerType: {
          title: '用工性质',
          formatter: (row) => this.categoryFormatter(store.state.sysconfigs.workerType, row, 'workerType')
      },
      state: {
          title: '在职状态',
          formatter: (row) => this.categoryFormatter(store.state.sysconfigs.state, row, 'state')
      },
      sex: {
          title: '性别',
          formatter: (row) => this.categoryFormatter(store.state.sysconfigs.sex, row, 'sex')
      },
      idCard: {
          title: '身份证',
          formatter: (row) => this.stringFormatter(row, 'idCard')
      },
      nation: {
          title: '民族',
          formatter: (row) => this.categoryFormatter(store.state.nationals, 'nation')
      },
      birthday: {
          title: '出生日期',
          formatter: (row) => this.stringFormatter(row, 'birthday')
      },
      age: {
          title: '年龄',
          formatter: (row) => this.stringFormatter(row, 'age')
      },
      positionType: {
          title: '职务级别',
          formatter: (row) => this.categoryFormatter(store.state.sysconfigs.positionType, 'positionType')
      },
      PtGraduateTime: {
          title: '在职毕业时间',
          formatter: (row) => this.stringFormatter(row, 'PtGraduateTime')
      },
      fistengagetime: {
          title: '首次聘任时间',
          formatter: (row) => this.stringFormatter(row, 'fistengagetime')
      },
      nativePlace: {
          title: '籍贯',
          formatter: (row) => this.nativePlaceFormatter(store.state.provinces, store.state.cities, row)
      },
      politicalStatus: {
          title: '政治面貌',
          formatter: (row) => this.categoryFormatter(store.state.sysconfigs.politicalStatus, row, 'politicalStatus')
      },
      joinPartyTime: {
          title: '入党时间',
          formatter: (row) => this.stringFormatter(row, 'joinPartyTime')
      },
      joinWorkTime: {
          title: '参加工作时间',
          formatter: (row) => this.stringFormatter(row, 'joinWorkTime')
      },
      createTime: {
          title: '进本系统时间',
          formatter: (row) => this.stringFormatter(row, 'createTime')
      },
      source: {
          title: '来源渠道',
          formatter: (row) => this.categoryFormatter(store.state.sysconfigs.channels, row, 'source')
      },
      departmentId: {
          title: '现工作单位',
          formatter: (row) => this.departFormater(store.state.departments, row, 'departmentId')
      },
      FtEducation: {
          title: '全日制教育最高学历',
          formatter: (row) => this.categoryFormatter(store.state.sysconfigs.FtEducation, row, 'FtEducation')
      },
      FtSchool: {
          title: '全日制教育毕业院校及专业',
          formatter: (row) => this.stringFormatter(row, 'FtSchool')
      },
      PtEducation: {
          title: '在职教育最高学历',
          formatter: (row) => this.categoryFormatter(store.state.sysconfigs.FtEducation, row, 'PtEducation')
      },
      PtSchool: {
          title: '在职教育毕业院校及专业',
          formatter: (row) => this.stringFormatter(row, 'PtSchool')
      },
      job: {
          title: '岗位级别',
          formatter: (row) => this.positionlevelFormatter(store.state.sysconfigs.postTypes,store.state.sysconfigs, row, 'job')
      },
      gwType: {
          title: '岗位类别',
          formatter: (row) => this.categoryFormatter(store.state.sysconfigs.postTypes, row, 'gwType')
      },
      positions: {
          title: '职务',
          formatter: (row) => this.positionFormater(store.state.sysconfigs.positions, row, 'positions')
      },
      FtGraduateTime: {
          title: '全日制毕业时间',
          formatter: (row) => this.stringFormatter(row, 'PtSchool')
      },
      tel: {
          title: '办公电话',
          formatter: (row) => this.stringFormatter(row, 'tel')
      },
      phone: {
          title: '手机号码',
          formatter: (row) => this.stringFormatter(row, 'phone')
      },
      married: {
          title: '婚姻状况',
          formatter: (row) => this.categoryFormatter(store.state.sysconfigs.married, row, 'married')
      },
      image: {
          title: '头像',
          formatter: (row) => this.stringFormatter(row, 'ptj')
      },
      ptj: {
          title: '专业技术职务',
          formatter: (row) => this.stringFormatter(row, 'ptj')
      },
      ptl: {
          title: '专业技术级别',
          formatter: (row) => this.categoryFormatter(store.state.sysconfigs.ptl, row, 'ptl')
      },
      firstSignTime: {
          title: '首次签订合同时间',
          formatter: (row) => this.stringFormatter(row, 'firstSignTime')
      },
      resume: {
          title: '个人简历',
          clickable: true,
          formatter: (row) => {
              return row
          }
      },
      baseInfo: {
          title: '基础信息',
          clickable: true,
          formatter: (row) => {
              return row
          }
      },
      extraInfo:{
          title: '补充信息',
          clickable: true,
          formatter: (row) => {
              return row
          }
      },
      socialReltaion: {
          title: '家庭及主要社会关系',
          clickable: true,
          formatter: (row) => {
              return row
          }
      },
      onlineWork: {
          title: '在职培训',
          clickable: true,
          formatter: (row) => {
            var educations = JSON.parse(row)
            var strContent = ''
            for(var i=0;i<educations.length;i++){
              strContent = strContent + educations[i].starttime+' ～ '+ educations[i].starttime+' 参加 ' + educations[i].traingname +' 培训'
            }
            return strContent
          }
      },
      continueTrain: {
          title: '继续教育',
          clickable: true,
          formatter: (row) => {
              var educations = JSON.parse(row)
              var strContent = ''
              for(var i=0;i<educations.length;i++){
                strContent = strContent + ' 学校: '+ educations[i].school +' 专业: ' + educations[i].discipline +' 继续教育 '
              }
              return strContent
          }
      },
      technicalPosition: {
          title: '专业技术职务',
          clickable: true,
          formatter: (row) => {
              return row
          }
      },
      takePart: {
          title: '参加活动（竞赛）情况',
          clickable: true,
          formatter: (row) => {
              return row
          }
      },
      projects: {
          title: '参加工程项目建设情况',
          clickable: true,
          formatter: (row) => {
              return row
          }
      },
      annualAssessment: {
          title: '年度考核',
          clickable: true,
          formatter: (row) => {
              return row
          }
      }
    }
  }

  getCloumns(){
    return [
      { prop: 'creatorName', label: '申请人', sortable: true, width: '130', formatter: this.stringFormater },
      { prop: 'createTime', label: '申请时间', sortable: true, width: '220', formatter: this.timeStampFormater },
      { prop: 'type', label: '变更类型', sortable: true, width: '150', formatter:(row,column) => this.getAppvoalType(row,column) },
      { prop: 'state', label: '申请状态', sortable: true, width: '150', formatter:(row,column) => this.getAppvoalStatus(row,column) },
      { prop: 'reason', label: '原因', sortable: true, width: '350', formatter: this.stringFormater }
    ]
  }

  getSubmitCols(){
    return [
      { prop: 'approverName', label: '待办人', sortable: true, width: '180', formatter: this.stringFormater },
      { prop: 'createTime', label: '申请时间', sortable: true, width: '180', formatter: this.timeStampFormater },
      { prop: 'type', label: '变更类型', sortable: true, width: '150', formatter:(row,column) => this.getAppvoalType(row,column) },
      { prop: 'reason', label: '原因', sortable: true, width: '350', formatter: this.stringFormater },
      { prop: 'state', label: '申请状态', sortable: true, width: '150', formatter:(row,column) => this.getAppvoalStatus(row,column) },
      { prop: 'ackTime', label: '审核时间', sortable: true, width: '180', formatter:this.timeStampFormater },
      { prop: 'comment', label: '审核意见', sortable: true, width: '150', formatter:this.stringFormater }
    ]
  }

  getDashDifferColumns(){
    return [
      { prop: 'operator', label: '操作者', width: '150', sortable: true, formatter: this.stringFormater },
      { prop: 'user', label: '姓名', width: '150', sortable: true, formatter: this.stringFormater },
      { prop: 'time', label: '变更时间', width: '180', sortable: true, formatter: (row, column) => {return util.date2str(new Date(row.time * 1000), "yyyy-MM-dd hh:mm")} },
      { prop: 'field', label: '变更属性', width: '180', sortable: true, formatter: (row,column) => this.fieldNameFormater(row,column,this.cols) },
      { prop: 'before', label: '变更前内容', width: '450', sortable: true, formatter: (row, column) => this.colFormater(row,column,this.cols,true) },
      { prop: 'after', label: '变更后内容', width: '450', sortable: true, formatter: (row, column) => this.colFormater(row,column,this.cols,false) }
    ]
  }

  colFormater(row,column,cols,before){
    var formatter = cols[row.field].formatter
    if(formatter){
      if(before){
        return formatter(row.before)
      }
      else{
        return formatter(row.after)
      }
    }
    
    else{
      if(before){
        return row.before
      }
      else{
        return row.after
      }
    }
  }

  fieldNameFormater(row,column,cols){
      return cols[row[column.property]].title
  }

  getDiffColumnsInfo(){
    return this.cols
  }

  getDiffCols(){
      return [
          {prop: 'name', label: '姓名', sortable: true, width: '180', formatter: util.stringFormater},
          {prop: 'field', label: '属性', sortable: true, width: '180', formatter: this.fieldFormater},
          {prop: 'before', label: '变更前', sortable: true, width: '180', formatter: this.beforeFormater},
          {prop: 'after', label: '变更后', sortable: true, width: '180', formatter: this.afterFormater}
      ]
  }

  getProcs(){
    return [
      {id:1,name:'同意'},
      {id:2,name:'拒绝'}
    ]
  }

  getTypes(){
    return [
        {id:0,name:'新增用户'},
        {id:1,name:'编辑用户'},
        {id:2,name:'删除用户'},
        {id:5,name:'月报申请'}
      ]
  }

  getStatus(){
      return [
          {id:0,name:'待处理'},
          {id:1,name:'同意'},
          {id:2,name:'拒绝'}
      ]
  }

  getApproval(approvalId,sucCallback,failedCallback){
    vue.http.post('/hr/approval/get?id='+approvalId).then(response => {
      console.log("get approval response" + response);
        if(sucCallback){
          if (response.body.result == 1) {
            console.log('get approval response ' + JSON.stringify(response.body));
            sucCallback(response.body.body)
          }
          else{
            failedCallback(response)
          }
        }
    }, response => {
      if(failedCallback){
        failedCallback(response)
      }
    })
  }

  agree(approval,sucCallback,failedCallback){
    vue.http.post('/hr/approval/agree?id='+approval.id+"&comment="+approval.comment).then(response => {
      console.log("agree approver response" + response);
        if(sucCallback){
          sucCallback(response)
        }
    }, response => {
      if(failedCallback){
        failedCallback(response)
      }
    })
  }

  reject(approval,sucCallback,failedCallback){
    vue.http.post('/hr/approval/reject?id='+approval.id+"&comment="+approval.comment).then(response => {
      console.log("reject approver response" + response);
        if(sucCallback){
          sucCallback(response)
        }
    }, response => {
      if(failedCallback){
        failedCallback(response)
      }
    })
  }
  
  stringFormatter(obj, prop) {
    return obj
  }

  categoryFormatter(categories,obj,prop){
    for (var index in categories) {
      if (categories[index].id == obj) {
        return categories[index].name
      }
    }
    return ''
  }

  departFormater(departments,obj,prop){
    if(!departments){
      return ''
    }
    console.log('departFormater:'+departments);
    for(var index in departments){
      if(departments[index].id == obj){
        return departments[index].name
      }
      else{
        var res = this.departFormater(departments[index].subDepartments,obj,prop)
        if(res){
          return res
        }
      }
    }
    return ''
  }

  positionlevelFormatter(postTypes,sysconfigs, positionLevel, prop){
    for(var index in postTypes){
      var positionLevels =sysconfigs['positionlevels_'+postTypes[index].id]
      for(var plIndex in positionLevels){
        if(positionLevel == positionLevels[plIndex].id){
          return positionLevels[plIndex].name
        }
      }
    }
    return ''
  }

  positionFormater(positions, obj, prop) {
      var position = ''
      var poss = []
      if(typeof(obj) == 'string'){
        poss = obj.split(',')
      }
      else if(obj instanceof Number){
        poss.push(obj)
      }
      if (poss) {
        for (var index in positions) {
          for (var posIndex in poss) {
            if (poss[posIndex] == positions[index].id) {
              if (position) {
                position = position + ',' + positions[index].name
              }
              else {
                position = positions[index].name
              }
            }
          }
        }
      }
      return position
  }

  nativePlaceFormatter(provinces, cities, nativePlace) {
      var strArray = nativePlace.split(',')
      var strNativePlace = null
      for (var index in provinces) {
        if (provinces[index].code == strArray[0]) {
          strNativePlace = provinces[index].name
          break
        }
      }

      for (var index in cities) {
        if (cities[index].code == strArray[1]) {
          if (!strNativePlace) {
            strNativePlace = cities[index].name
          }
          else {
            strNativePlace = strNativePlace + cities[index].name
          }
          break
        }
      }
    
    return strNativePlace
  }

  fieldFormater(row,column){
    if(isNotEmpty(row,column)){
      return differCols[row[column.property]].title
    }
  }

  beforeFormater(row,column){
    if(isNotEmpty(row,column)){
      var formatter = differCols[row.field].formatter
      return formatter(row.before)
    }
    return ''
  }

  afterFormater(row,column){
    if(isNotEmpty(row,column)){
      var formatter = differCols[row.field].formatter
      return formatter(row.after)
    }
    return ''
  }

  getAppvoalType(row, column){
    var status = row[column.property]
    for(var index in this.getTypes()){
      if(this.getTypes()[index].id == status){
        return this.getTypes()[index].name
      }
    }
    return ''
  }

  ack(row,sucCallback,failedCallback){
    vue.http.post('/hr/approval/get?id='+row.id).then(response => {
      console.log("get approver response" + response);
        if(sucCallback){
          sucCallback(response)
        }
    }, response => {
      if(failedCallback){
        failedCallback(response)
      }
    })
  }

  getAppvoalStatus(row, column){
    var status = row[column.property]
    for(var index in this.getStatus()){
      if(this.getStatus()[index].id == status){
        return this.getStatus()[index].name
      }
    }
    return ''
  }

  timeStampFormater(row, column) {
    if (isNotEmpty(row, column)) {
      return approveUtils.timeStamp2String(row[column.property])
    }
    return ''
  }

  getUserApprovals(sucCallback,failedCallback){
    vue.http.get('/hr/approval/listMyHandles').then(response => {
      console.log("list approver response" + response);
        if(sucCallback){
          sucCallback(response)
        }
    }, response => {
      if(failedCallback){
        failedCallback(response)
      }
    })
  }

  getUserSubmits(sucCallback,failedCallback){
    vue.http.get('/hr/approval/listMySubmit').then(response => {
      console.log("list approver response" + response);
        if(sucCallback){
          sucCallback(response)
        }
    }, response => {
      if(failedCallback){
        failedCallback(response)
      }
    })
  }

  listDiffers(data,sucCallback,failedCallback){
    vue.http.get('/hr/approval/listDiffers?startTime='+data.startTime+'&endTime='+data.endTime).then(response => {
      console.log("list listDiffers response" + response);
        if(sucCallback){
          sucCallback(response)
        }
    }, response => {
      if(failedCallback){
        failedCallback(response)
      }
    })
  }

  static timeStamp2String(time) {
    var datetime = new Date();
    datetime.setTime(time * 1000);
    var year = datetime.getFullYear();
    var month = datetime.getMonth() + 1;
    var date = datetime.getDate();
    var hour = datetime.getHours();
    var minute = datetime.getMinutes();
    return year + "/" + month + "/" + date + " " + hour +":" + minute;
  }

  listApprover(sucCallback,failedCallback){
    if(store.state.approvers && store.state.approvers.length >0){
      return
    }
    vue.http.post('/hr/approval/listApprover').then(response => {
      console.log("list approver response" + response);
      if (response.body.result == 1) {
        store.commit('SET_APPROVERS', response.body.body)
        if(sucCallback){
          sucCallback(response)
        }
      }
    }, response => {
      if(failedCallback){
        failedCallback(response)
      }
    })
  }
}
